#! /usr/bin/env python
#coding=utf-8

import os
import pickle
import time
import threading

from ljnetworkapi import LJUserSession
from ljvisualize import LJVisualizer

class MyThread(threading.Thread):
    
    def __init__(self, threadID):
        threading.Thread.__init__(self)
        self.threadID = threadID
        
    def setParams(self, f, *args):    
        self.args = args
        self.f = f        
    
    def run(self):
        self.f(*self.args)                
    

def scanUser(LJUserName, depth, skipCommunities, collectInterests, mutualFriendsOnly, verboseMode, updateCallback):

    SCAN_DEPTH = int(depth)

    # start collecting data
    session = LJUserSession(LJUserName, "")
    # setup scan params
    session.setVerbose(verboseMode)
    session.setSkipCommunities(skipCommunities)
    session.setCollectInterests(collectInterests)
    session.setUpdateCallback(updateCallback)
    session.setScanMutualFriendsOnly(mutualFriendsOnly)
    
    print "Traversing all the friends of LJ user " + LJUserName + " ( max depth = " + str(SCAN_DEPTH) + " ), this can take a long time... \n", 
    output = session.scanAllFriends(SCAN_DEPTH)
    print "Done"

    print "Saving to file... ",
    # save output file (serialized)
    f = open(LJUserName, "wb")
    pickle.dump(output, f, pickle.HIGHEST_PROTOCOL)
    f.close()

    # save output file (human readable)
    """
    f = open(LJUserName + ".txt", "wt")
    tmp = output.toHR()
    for item in tmp:
        f.write(str(item) + '\n')
    f.close()
    """
    print "Ok"

    session.getStatDataStruct().showStats()

def drawGraph(LJUserName):    
    
    # run visualizer with the collected data
    print "Reading data, please wait...", 
    f = open(LJUserName, "rb")
    output = pickle.load(f)
    f.close()
    print "Ok"
    
    print "Preparing...",
    visualizer = LJVisualizer(output)
    visualizer.initPyGame()
    print "Ok"
    
    while(visualizer.m_isAlive):
        # render loop        
        visualizer.update()
        visualizer.paint()
        # yield
        time.sleep(0)
